package com.mycomp;

import java.io.File;
import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

@ManagedBean
public class ReportTemplate {
	
	private String text;
    private File file;
    private String[] check;
	
	public void uploadData(){
		System.out.println("hi");
	}
	
	 public void submit() {
		 FacesContext context = FacesContext.getCurrentInstance();
		 ExternalContext externalContext = context.getExternalContext();
		 Workbook workbook = new HSSFWorkbook();
		 Sheet sheet = workbook.createSheet("sheet title");
		 int rowIndex = 0;

		// for (Item item : items) {
		     Row row = sheet.createRow(rowIndex++);
		     int columnIndex = 0;

		     row.createCell(columnIndex++).setCellValue("1");
		     row.createCell(columnIndex++).setCellValue("2");
		     row.createCell(columnIndex++).setCellValue("3");
		     // ...
		// }
		     externalContext.responseReset(); 
		     externalContext.setResponseContentType("application/vnd.ms-excel");
		     externalContext.setResponseHeader("Content-Disposition", "attachment;filename=export.xls");
		     try {
				workbook.write(externalContext.getResponseOutputStream());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		     context.responseComplete(); // Prevent JSF from performing navigation.    
		     
	    }

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String[] getCheck() {
		return check;
	}

	public void setCheck(String[] check) {
		this.check = check;
	}
	
	 private UploadedFile uploadedFile;

	    public void submit1() throws IOException {
	        String fileName = FilenameUtils.getName(uploadedFile.getName());
	        String contentType = uploadedFile.getContentType();
	        byte[] bytes = uploadedFile.getBytes();

	        // Now you can save bytes in DB (and also content type?)

	        FacesContext.getCurrentInstance().addMessage(null, 
	            new FacesMessage(String.format("File '%s' of type '%s' successfully uploaded!", fileName, contentType)));
	    }

	    public UploadedFile getUploadedFile() {
	        return uploadedFile;
	    }

	    public void setUploadedFile(UploadedFile uploadedFile) {
	        this.uploadedFile = uploadedFile;
	    }

}
